#!/usr/bin/env python3

import pickle
import os

class Student:
    __lastID = 1

    def __init__(self, name, **kargs):
        self.name = name
        self.sex = '男'
        self.age = 20
        self.en = 0
        self.cn = 0
        self.cmpField = "name"
        self.__dict__.update(kargs)

        self.id = Student.__lastID
        Student.__lastID += 1

    @staticmethod
    def getLastID():
        return Student.__lastID

    @staticmethod
    def setLastID(val):
        Student.__lastID = val

    def __setattr__(self, name, value):
        #  print("name: ", name, ", value: ", value)
        if name == "id" and name in self.__dict__:
            print("setattr 学号不允许修改....")
        else:
            self.__dict__[name] = value

    def set(self, **kargs):
        if "id" in kargs:
            print("学号不允许修改...")
            return self
        self.__dict__.update(kargs)
        return self

    def __add__(self, s):
        return str(self) + s

    def __radd__(self, s):
        return s + str(self)

    def copy(self):
        return Student(**self.__dict__)

    def __eq__(self, o):
        return self.cmp(o, self.cmpField)

    def cmp(self, o, field='name'):
        return getattr(self, field) == getattr(o, field)

    def __str__(self):
        return ("学号: %d, 姓名: %s, 性别: %s, 年龄: %d, 英文: %d, 语文: %d"
                    % (self.id, self.name, self.sex,
                       self.age, self.en, self.cn))

    @staticmethod
    def load(fileObj):
        if type(fileObj) == str:
            fileObj = open(fileObj, "rb")
        return pickle.load(fileObj)

    def dump(self, fileObj):
        if type(fileObj) == str:
            fileObj = open(fileObj, "wb")
        pickle.dump(self, fileObj)
        return self

if __name__ == "__main__":
    if os.path.exists("./db"):
        s = Student.load("./db")
    else:
        s = Student('张三')
    #  s.age = 16
    s.id = 66
    print("+++++" + s)

    o = Student('张三')
    setattr(o, 'sex', "女")
    print("+++++" + o)

    #  c = s.copy()
    #  c.age = 10
    #  c.sex = '女'
    #  print(c)
    #  print(s)

    #  print(id(s), id(c))
    #  print(s == o)
    #  c.cmpField = 'sex'
    #  print(s.cmp(c, 'en'))

    #  s.dump("./db")

